import axios from "axios";
import QS from "qs";
import store from "../store";
import router from '../router';
import { Toast } from "vant";

// export const BASE = process.env.NODE_ENV === 'development' ? "http://192.168.1.119/api" : 'http://ttssc.567nm.cn/api'
// export const BASE = "http://192.168.1.119/api"
//测试服
// export const BASE = "http://ttssc.567nm.cn/api"
// 正式服
export const BASE = "http://www.dayweizhuan.com/api"
// 请求超时时间
axios.defaults.timeout = 10000;

// post请求头
axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded;charset=UTF-8";
axios.defaults.validateStatus = function(status) {
  return status >= 200; // default
};

// 请求拦截器
axios.interceptors.request.use(
  config => {
    // token
    const token = store.state.token;
    token && (config.headers.token = token);
    return config;
  },
  error => {
    return Promise.error(error);
  }
);

// 响应拦截器
axios.interceptors.response.use(
  res => {
    if (res.data.status_code == 403) {
      Toast("请登录");
      router.replace("/login");
      return Promise.reject(new Error(res.data.message));
    }
    if (res.data.status_code >= 400) {
    	if(res.data.errors) {
				for(var obj in res.data.errors) {
					for(var i = 0; i < res.data.errors[obj].length; i++) {
						Toast(res.data.errors[obj][i]);
					}
				}
				return Promise.reject(new Error(res.data.message));
      }
      Toast(res.data.message);
      return Promise.reject(new Error(res.data.message));
    }

    return res;
  },
  error => Promise.reject(error)
);

export function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios
      .get(BASE + url, {
        params: params
      })
      .then(res => {
        resolve(res);
      })
      .catch(err => {
        reject(err);
      });
  });
}

export function post(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .post(BASE + url, QS.stringify(params))
      .then(res => {
        resolve(res);
      })
      .catch(err => {
        reject(err);
      });
  });
}
